# coding=utf-8
from flask import Blueprint, request, jsonify, json, make_response, redirect, g
from common.models.Food import Food, FoodType
from common.models.Order import Order
from common.libs.user.UserLibs import UserLibs
from common.libs.Helper import ops_render, get_current_time, create_pages
from common.libs.UrlManager import UrlManager
from sqlalchemy import or_
from application import app,db
from web.controllers.BaseControllerHelper import *
from .Helper import *

route_food = Blueprint( 'food_page', __name__ )


@route_food.route( "/index" )
def index():
    """
    列表页
    :return:
    """
    context = {}
    req = request.values
    shop_id = g.current_user.shop_id
    query, pages, offset, limit = create_pages(10, Food.query.filter_by(shop_id=shop_id), request)
    if 'mix_kw' in req and len(req['mix_kw']) > 0 :
        query = query.filter(Food.name.ilike("%{0}%".format(req['mix_kw'])))

    if 'food_type_id' in req and int(req['food_type_id']) > 0:
        query = query.filter_by(food_type_id=int(req['food_type_id']))

    food_list = query.order_by(Food.id.desc()).all()[offset:limit]
    food_type_list = FoodType.query.order_by(FoodType.id.desc()).all()
    context["food_list"] = food_list
    context["pages"] = pages
    context['search_con'] = req
    context['food_type_list'] = food_type_list
    return ops_render("/food/index.html", context=context)

@route_food.route( "/set" , methods=["GET", "POST"])
def set() :
    """
        添加或修改
        :return:
        """
    context = {}
    req = request.values
    resp = gene_response(msg="操作成功~~")
    food_info = None
    food_type_list = FoodType.query.all()
    if request.method == "GET":
        id = int(req.get("id", 0))
        if id:
            food_info = Food.query.filter_by(id=id).first()
        context['food_info'] = food_info
        context['food_type_list'] = food_type_list
        return ops_render("/food/set.html", context=context)
    return jsonify(resp)

@route_food.route("/ops",methods=["POST"])
def ops():
    resp = { 'code':200,'msg':'操作成功~~','data':{} }
    req = request.values

    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    if not id :
        resp['code'] = -1
        resp['msg'] = "请选择要美食~~"
        return jsonify(resp)

    if act not in [ 'remove','recover' ]:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)

    food_info = Food.query.filter_by( id = id ).first()
    if not food_info:
        resp['code'] = -1
        resp['msg'] = "指定美食不存在~~"
        return jsonify(resp)

    if act == "remove":
        food_info.is_delete = 1
    elif act == "recover":
        food_info.is_delete = 0

    food_info.updated_time = get_current_time()
    db.session.add(food_info)
    db.session.commit()
    return jsonify( resp )